/**
 * 按钮组
 * @function useButtons
 * @Author: linzy
 * @Date: 2022-05-17
 * @param {button[]} buttons - 按钮数组
 * @param {boolean} disabled - 按钮是否全部禁用
 * @param {*} payload - 为要穿给onClick的参数 复写了button的onClick 方便传参
 * @property {object} button - 按钮对象
 * @param {string} text - 按钮的文本
 * @param {function} onConfirm - Popconfirm组件的点击确定事件
 * @param {object} confirmProps - Popconfirm组件的传参对象
 * @param {string} title - Tooltip title属性
 * @param {object} confirmProps - Tooltip传参对象
 * @param {string} type=primary - 按钮的类型 默认为primary
 * @param {string} onClick - Button组件 title属性
 * @param {object} buttonProps - Button组件传参对象
 * @param {function} render - 自定义 实现非按钮标签
 * @example <caption>form表单的按钮组、页面头部的按钮组比如新建等</caption>
 * import { useButtons } from '@/hooks'
 * const buttons = [
 *   { text: '跳转', icon: 'link',href: 'xxx'},
 *   { children: '保存', , onClick: (form) => btnClick(form)},
 * ]
 * const buttonsRender = useButtons({buttons,disabled,payload:form})
 */
import { Button, Popconfirm, Tooltip } from "antd";
import { setOutAttrs, setDefaultAttrs, getBoolean } from "@/hooks/tools";

export default props => {
  const { buttons = [], disabled, payload } = props;
  const filterButtons = buttons.filter(item => getBoolean(item.show, payload));
  return filterButtons.map((item, index) => {
    const {
      text,
      label,
      onConfirm,
      confirmProps = {},
      title,
      tooltipProps = {},
      disabled,
      onClick,
      render,
      ...buttonProps
    } = item;
    // 处理 buttonProps
    setOutAttrs(buttonProps, { onClick });
    setDefaultAttrs(buttonProps, {
      children: text || label,
      type: "primary"
    });
    disabled && (buttonProps.disabled = buttonProps.disabled ?? true);
    if (index > 0) {
      buttonProps.style = { marginLeft: "8px", ...buttonProps.style };
    }
    setOutAttrs(confirmProps, { onConfirm });
    setDefaultAttrs(confirmProps, {
      title: `确定要${text}吗？`
    });
    setOutAttrs(tooltipProps, { title });
    function overrideClick(e) {
      buttonProps.onClick && buttonProps.onClick(payload, e);
    }
    return (
      <>
        {render ? (
          render(item, index)
        ) : confirmProps.onConfirm && !disabled ? (
          <Popconfirm
            {...confirmProps}
            onConfirm={() => {
              confirmProps.onConfirm(payload);
            }}
          >
            <Tooltip {...tooltipProps}>
              <Button type="primary" {...buttonProps} />
            </Tooltip>
          </Popconfirm>
        ) : (
          <Tooltip {...tooltipProps}>
            <Button type="primary" {...buttonProps} onClick={overrideClick} />
          </Tooltip>
        )}
      </>
    );
  });
};
